package com.escom.service;

import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.escom.healthlc.entidad.PositionORM;
import com.escom.utils.Constantes;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Observable;
import java.util.Observer;
import java.util.StringTokenizer;

/**
 * Created by Carlos on 21/04/2014.
 */
public class PositionService implements Runnable {

    private PositionObservable positionObservable = new PositionObservable();
    private PositionORM position;
    private FragmentActivity fragmentActivity;

    public PositionService(PositionORM position, FragmentActivity fragmentActivity) {
        this.position = position;
        this.fragmentActivity = fragmentActivity;
    }

    private class PositionObservable extends Observable {
        @Override
        public void notifyObservers() {
            setChanged();
            super.notifyObservers();
        }
    }

    @Override
    public void run() {
        try {
            byte[] buffer = new byte[32];
            MulticastSocket multicastSocket = new MulticastSocket(Constantes.PORT_ACELEROMETRO);
            multicastSocket.joinGroup(InetAddress.getByName(Constantes.GROUP));
            DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
            while (true) {
                multicastSocket.receive(datagramPacket);
                String data = new String(datagramPacket.getData());
                StringTokenizer stringTokenizer = new StringTokenizer(data, ",");
                String positionValue = stringTokenizer.nextToken();
                Log.d(Constantes.LOG_ID, this.getClass().getName() + " El valor de la posicion es : " + positionValue);
                position.setPosition(positionValue);
                fragmentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        positionObservable.notifyObservers();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addObserver(Observer observer) {
        positionObservable.addObserver(observer);
    }
}
